package user

import (
	"time"

	"gitee.com/xiaoyutab/gatway/config"
	"gitee.com/xiaoyutab/gatway/model"
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 用户注册方法
//
//	c	用户信息
//	ip	客户端IP地址
func Regedit(c *model.User, ip string) error {
	if c == nil {
		return xerror.New("用户数据错误")
	}
	if c.Id > 0 {
		return xerror.New("用户数据错误")
	}
	if c.Password == "" {
		return xerror.New("用户密码不能为空")
	}
	if c.Nickname == "" {
		c.Nickname = "游客" + time.Now().Format("01021504")
	}
	// 密码生成
	c.RandCode = GetRand()
	pass_new, err := Passwd(c.Password, c.RandCode)
	if err != nil {
		return err
	}
	c.Password = pass_new
	// 检测用户登录账户是否被占用
	inf, err := GetInfoByUserName(c.Username)
	if err != nil {
		return err
	}
	if inf.Id > 0 {
		return xerror.New("用户登录账户名已存在")
	}
	// 初始值设置
	c.RegTime = time.Now().Format(time.DateTime)
	c.LoginTime = config.DATETIME_MIN
	c.LockTime = config.DATETIME_MIN
	db := config.DB.Save(c)
	if db.Error != nil {
		return xerror.To(err)
	}
	if db.RowsAffected <= 0 {
		return xerror.New("数据插入失败")
	}
	// 记录日志
	Log(c.Id, 1, ip)
	// 缓存设置
	xcache.SetStruct(xcache.Key("service.user.get.info.by.id", c.Id), c)             // 用户ID缓存
	xcache.SetStruct(xcache.Key("service.user.get.info.by.username", c.Username), c) // 用户Username缓存
	return nil
}
